/*
 * Copyright (c) 2021 The red-star Project
 *
 * Licensed under the Apache License, version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.inyourcode.core.spring;

import com.inyourcode.core.util.StackTraceUtil;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.util.Properties;

/**
 *
 *
 * @author JackLei
 */
public abstract class AppBootstrap {
    private AnnotationConfigApplicationContext configApplicationContext = new AnnotationConfigApplicationContext();
    private Properties appProperties;

    public void start(String args[]) throws AppException {
        if (args.length < 1) {
            throw new AppException("Please enter the program startup configuration");
        }

        String appPropertiesName = args[0];
        try {
            appProperties = PropertiesLoaderUtils.loadProperties(new ClassPathResource(appPropertiesName));
        } catch (IOException e) {
            throw new AppException(String.format("Failed to load startup configuration, properteis:{}, exception:{}",
                    appPropertiesName, StackTraceUtil.stackTrace(e)));
        }

        configApplicationContext.getEnvironment().getPropertySources().addLast(new PropertiesPropertySource(appPropertiesName, appProperties));
        configApplicationContext.register(getAppConfigClass());
        configApplicationContext.refresh();
    }

    public abstract Class getAppConfigClass();
}
